<?php
/*************************************************************************************
 *
 *	FileName: LetterDAO.php
 *	Desc    : DAO for letters
 *	Author  : Seal
 *	Date    : 2009-12-29
 *
 *************************************************************************************/

	include_once ( "AbstractDAO.php" );
	class LetterDAO extends AbstractDAO
	{
		
		function SendLetter( $receiverIDs /* an array here*/, $senderID, $senderName, $title, $content )
		{
			$now=GetCurrentDate();
			$userDAO=GetUserDAO();
			
			if(is_array($receiverIDs))
			{
				$arr_receiverID=$receiverIDs;
			}
			else
			{
				$arr_receiverID=array($receiverIDs);
			}
			
			//$arr_receiverID = $receiverIDs;
			/*
			 *  >>>>> DO NOT <<<< use the userDAO->InBlackList to filter out the user
			 *  It's inefficient. Should use the method below!!
			 *  
			 *  Yawei 
			 */		
			if($senderID>0)
			{
				$blackList =  $userDAO->GetBlackList( $senderID );
				
				if( $blackList ){
					$blackList = explode( ',', $blackList );
					for( $i = 0; $i < count($arr_receiverID); $i++)
					{
						if( in_array( $arr_receiverID[$i], $blackList ) == true )
							array_splice($arr_receiverID, $i, 1);
					}
				}
			}
			
			if( count($arr_receiverID) <= 0 )
				return false;
			else
			{
				$receiverIDs = implode(',', $arr_receiverID);
				$receiverList=$this->db->GetPlan("select id, nick from user_basic_info where id in ($receiverIDs)");
				try
		    	{
			    	$this->db->BeginTransaction();	
					$sql = "insert into letter( sender_id, sender_name, receiver_id, receiver_name, title, content, date, is_read )
							values" ;	
					
					for( $i = '0'; $i < count($receiverList); $i++ )
					{
						$this->db->Update("update user_statistic set letter_count=letter_count+1 where user_id=".$receiverList[$i]['id']);
						if( $i > '0' )
							$sql .= ',';
						$sql .="( $senderID, '$senderName', ".$receiverList[$i]['id'].", '".$receiverList[$i]['nick']."', '$title', '$content', '$now', 0 )" ; 
					}
					$this->db->Insert( $sql );	
					
					$sql = "update user_statistic set send_letter_count = send_letter_count +".count($receiverList)." where user_id = $senderID";
					$this->db->Update( $sql );
					$this->db->Commit();
		    		return true;
		    	}
				catch( Exception $e)
		    	{
		    		$this->db->Rollback();
		    		return false;
		    	}
		    	
			}
		}
			
		function ReceiveLetterByID( $receiver_id, $sortby = 'isreaden', $startpos = 0, $num = MAIL_PER_PAGE )
		{
			
			// for query optimization here, we use application join instead of database --yawei
			$sql = "select i.id 
						from letter i
						where receiver_id = $receiver_id
						  and receiver_del = 0 ";
			if( $sortby == 'isreaden' )
				$sql .= " order by is_read, id desc";
			else 
				$sql .= " order by id desc";
				
				
			$sql .= " limit $startpos, $num ";
			
			$result = $this->db->GetPlan( $sql );
			
			if( !$result )
				return false;
		
			$ids = '';
			foreach( $result as $key => $value )
				$ids .= $value['id'] . ',';
				
			$ids = rtrim( $ids, ',');
			
			$sql = "select id, date, sender_name, title, is_read, sender_id
					from letter
					where id in ($ids)";
				
			return $this->SortByIdArray( $this->db->GetPlan( $sql ), explode(',', $ids) );
		}
		
		/**********************************************************
		 *
		 * to get all the mails for the output mailbox
		 *
		 **********************************************************/
		function GetOutLetters( $sender_id, $startpos = 0, $num = MAIL_PER_PAGE )
		{
			
			// for query optimization here, we use application join instead of database --yawei
			$sql = "select i.id 
						from letter i
						where sender_id = $sender_id
						  and sender_del = 0 
						order by id desc 	
						limit $startpos, $num ";
			
			$result = $this->db->GetPlan( $sql );
			
			if( !$result )
				return false;
		
			$ids = '';
			foreach( $result as $key => $value )
				$ids .= $value['id'] . ',';
			
			$ids = rtrim( $ids, ',');
			
			$sql = "select id, date, receiver_name, title 
					from letter
					where id in ($ids)";

			return $this->SortByIdArray( $this->db->GetPlan( $sql ), explode(',', $ids) );
		}
		
		
		function GetLetterContent( $mailid, $userid )
		{
			$sql = "select content, sender_id
					  from letter
					 where id = $mailid 
					   and receiver_id = $userid ";
			
			return $this->db->GetRow( $sql );
		}
		
		function GetOutLetterContent( $mailid, $userid )
		{
			$sql = "select content
					  from letter
					 where id = $mailid 
					   and sender_id = $userid";
			
			return $this->db->GetValue( $sql );
		}
		
		function DeleteLetterFromReceiver( $mailids, $userid )
		{
			try
	    	{
		    	$this->db->BeginTransaction();	
		    	$sql = "update letter
		    			set receiver_del = 1
		    			where receiver_id = $userid and id in( $mailids)";
								
				$this->db->Update( $sql );
				$sql = "delete from letter
						where receiver_id = $userid 
						  and id in($mailids)
						  and receiver_del = 1
						  and sender_del = 1";
				
				$this->db->Update( $sql );
				
				$mails=explode(',', $mailids);
				
				
				$num=count($mails);
				
				$sql = "select letter_count from user_statistic where user_id = $userid";
				$letterCount = $this->db->GetValue( $sql );
				
				if( $letterCount < $num ) {
					$Logger = GetLogger();
					$Logger->error( "error from delete receiver mail: count: $num, ori count: $letterCount, userid: $userid" );
				}
				
				$sql="update user_statistic set letter_count=(letter_count-$num) where user_id=$userid";
				$this->db->Update( $sql );
				$this->db->Commit();
	    		return true;
	    	}
			catch( Exception $e)
	    	{
	    		$this->db->Rollback();
	    		return false;
	    	}
	    	
		}
		
		function DeleteLetterFromSender( $mailids, $userid )
		{
			try
	    	{
		    	$this->db->BeginTransaction();	
		    	$sql = "update letter
		    			set sender_del = 1 
		    			where sender_id = $userid and id in( $mailids)";
				$this->db->Update( $sql );
				$sql = "delete from letter
						where sender_id = $userid 
						  and id in($mailids)
						  and sender_del = 1
						  and receiver_del = 1";
				
				$this->db->Update( $sql );
				
				$mails=explode(',', $mailids);
				$num=count($mails);
				
	    		$sql = "select letter_count from user_statistic where user_id = $userid";
				$letterCount = $this->db->GetValue( $sql );
				
				if( $letterCount < $num ) {
					$Logger = GetLogger();
					$Logger->error( "error from delete sender mail: count: $num, ori count: $letterCount, userid: $userid" );
				}
				
				
				$sql="update user_statistic set send_letter_count = (send_letter_count - $num) where user_id=$userid";
				$this->db->Update( $sql );
				$this->db->Commit();
	    		return true;
	    	}
			catch( Exception $e)
	    	{
	    		$this->db->Rollback();
	    		return false;
	    	}
	    	
		}
		
		function LabelRead( $isread, $mailids, $userid )
		{
			$sql = "update letter
					set is_read = $isread 
					where receiver_id = $userid and id in($mailids)";
			
			return $this->db->Update( $sql );			
		}
		
		/**********************************************************
		 *	Get the total numbers of the mail of the user
		 *	Seal Created by 2010-1-2
		 **********************************************************/
		function GetInLetterCount( $userid )
		{
			$sql = " select count(*)
					 from letter  
					 where receiver_id = $userid 
					   and receiver_del = 0";
			
			return $this->db->GetValue( $sql );
		}
		
		function GetInLetterUnreadCount( $userid )
		{
			$sql = " select count(*)
					 from letter  
					 where receiver_id = $userid 
					   and is_read = 0
					   and receiver_del = 0";
			
			return $this->db->GetValue( $sql );
		}
		
		function GetOutLetterCount( $userid )
		{
			$sql = " select send_letter_count
					 from user_statistic  
					 where user_id = $userid ";
			
			return $this->db->GetValue( $sql );
		}
			
	
	}

?>